package com.yifi.system.controller;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.core.Path;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.yifi.common.DBHelper;
import com.yifi.common.base.BaseController;

@Path(value="/sysoption",viewPath = "/")
public class SysOptionController extends BaseController {

	public void index() {
		render("system/sysoption.html");
	}

	public void list() {

		String sql = "select t1.*,t1.cname as name,t1.cvalue as value,t1.cvalue as cvalue_t "
				+ " from sys_option t1  order by isort";
		List<Record> listRecord = Db.find(sql);
		for (Record r : listRecord) {
			Record editor = new Record();
			Record options = new Record();
			String cvalue = DBHelper.GetString(r, "cvalue");
			String ctype = DBHelper.GetString(r, "ctype");

			if (ctype.equals("输入")) {
				editor.set("type", "textbox");
			} else if (ctype.equals("选择")) {
				editor.set("type", "combobox");
				options.set("editable", false);
				String cch = DBHelper.GetString(r, "cch");// 选项
				if (!cch.equals("")) {
					JSONArray jsonArray = JSONArray.parseArray(cch);
					for (int i = 0; i < jsonArray.size(); i++) {// 查找选项翻译文本
						JSONObject jsonJ = jsonArray.getJSONObject(i);
						if (jsonJ.getString("value").equals(cvalue)) {
							String cvalue_t = jsonJ.getString("text");
							r.set("cvalue_t", cvalue_t);
							break;
						}
					}
					options.set("data", jsonArray);
				}
			}

			editor.set("options", options);
			r.set("editor", editor);
		}
		renderJson(listRecord);

	}

	public void save() {

		String jsonstr = getPara("data");

		List<String> sqlList=new ArrayList<String>();
		JSONArray jsonArray = JSONArray.parseArray(jsonstr);
		for (int i = 0; i < jsonArray.size(); i++) {
			JSONObject jsonJ = jsonArray.getJSONObject(i);
			String id = jsonJ.getString("id");
			String cvalue = jsonJ.getString("value");
			String sql="update sys_option set cvalue='" + cvalue + "'  where id='" + id + "' ";
			sqlList.add(sql);
		}
		
		if(Db.batch(sqlList, sqlList.size()).length>0)
		{
			renderJson(success("保存成功！"));
		}
		else
		{
			renderJson(error("保存失败！"));
		}
	}

	// 设置界面
	public void set() {
		render("system/sysoptionset.html");
	}
	
	public void getlist()
	{
		String sql = "select t1.*  from sys_option t1  order by isort";
		List<Record> listRecord = Db.find(sql);
		renderJson(listRecord);
	}

}
